<?php

namespace common\models;

use Yii;
use common\helpers\FileHelper;
use common\helpers\Url;
use common\helpers\IpHelper;

/**
 * This is the model class for table "{{%attachment}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $path 保存路径
 * @property string $original_name 原始名称
 * @property string $size 文件大小（单位：字节）
 * @property string $channel 远端上传通道
 * @property int $isimage 是否图片
 * @property int $width 宽度
 * @property int $height 高度
 * @property string $download 浏览或者下载次数
 * @property string $ip 上传IP地址
 * @property string $auth_token 校验Token
 * @property string $site_id 来源站点ID
 * @property int $status 附件状态
 * @property string $created_at
 * @property string $updated_at
 */
class Attachment extends \common\db\ActiveRecord {

    use \common\traits\Constants;

    const STATUS_DELETED = -1;
    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    public $channelCross = false;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%attachment}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'size', 'isimage', 'width', 'height', 'download', 'ip', 'site_id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['path', 'original_name', 'auth_token'], 'required'],
            [['path', 'original_name'], 'string', 'max' => 255],
            [['channel'], 'string', 'max' => 20],
            [['auth_token'], 'string', 'max' => 32],
            [['path'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'path' => '保存路径',
            'original_name' => '原始名称',
            'size' => '文件大小（单位：字节）',
            'channel' => '远端上传通道',
            'isimage' => '是否图片',
            'width' => '宽度',
            'height' => '高度',
            'download' => '浏览或者下载次数',
            'ip' => '上传IP地址',
            'auth_token' => '校验Token',
            'site_id' => '来源站点ID',
            'status' => '附件状态',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function getFilePath() {
        return Yii::getAlias('@uploads') . $this->path;
    }

    public function generateToken() {
        $string = implode('', $this->attributes);
        $this->auth_token = md5($string);
    }

    /**
     * 
     * @param \yii\web\UploadedFile $file
     * @param type $directoy
     * @return boolean
     */
    public static function upload($file, $directoy = 'default', &$msg = '') {
        if (!($file instanceof \yii\web\UploadedFile)) {
            return false;
        }
        $filename = FileHelper::buildUploadFileName($file->extension);
        $path = '/attachments/' . $directoy . '/' . date('Ym/d') . '/';
        $savepath = Yii::getAlias('@uploads') . $path;
        FileHelper::createDirectory($savepath);

        $file->saveAs($savepath . $filename);
        if ($file->getHasError()) {
            $msg = $file->error;
            return false;
        }

        $model = static::instance();
        $model->attributes = [
            'user_id' => Yii::$app->user->id,
            'path' => $path . $filename,
            'original_name' => $file->name,
            'size' => $file->size,
            'channel' => 'OSS',
            'isimage' => 0,
            'ip' => IpHelper::ip(),
        ];
        $model->generateToken();

        if ($model->save()) {
            return $model;
        }
        return false;
    }

    public function afterSave($insert, $changedAttributes) {
        parent::afterSave($insert, $changedAttributes);

        $path = ltrim($this->path, '/');
        if (YII_ENV_PROD && $this->channelCross === false) {
            $path = ltrim($this->path, '/');
            Yii::$app->alioss->putObjectACL(ltrim($this->path, '/'), 'public-read');
        }
    }

    public function fields() {
        return [
            'id',
            'user_id',
            'path',
            'url' => function() {
                return Url::attach($this->path);
            },
            'size',
            'channel',
            'isimage',
            'width',
            'height',
            'download',
            'ip' => function() {
                return IpHelper::long2ip($this->ip);
            },
        ];
    }

}
